import 'package:game/service/network.dart';
import 'package:flutter/material.dart';

class HallPage extends StatefulWidget {
  @override
  _HallPageState createState() => _HallPageState();
}

class _HallPageState extends State<HallPage>
    with AutomaticKeepAliveClientMixin {
  List<Score> _data;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _data = [];
    getScore().then((data) {
      setState(() {
        data.forEach((d) {
          if(!_data.contains(d)) {
            _data.add(d);
          }
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: Container(
        padding: EdgeInsets.all(8.0),
        child: ListView.builder(
          itemCount: _data.length,
          itemBuilder: (context, index) {
            var item = _data[index];
            return MyListItem(item);
          },
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  Future<void> _onRefresh() {
    return getScore().then((data) {
      setState(() {
        data.forEach((d) {
          if(!_data.contains(d)) {
            _data.add(d);
          }
        });
      });
    });
  }
}

class MyListItem extends StatelessWidget {
  final Score item;

  MyListItem(this.item);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(5.0),
          child: ListTile(
            onTap: () {},
            key: ValueKey(item.toString()),
            leading: CircleAvatar(
              backgroundColor: Colors.blueAccent,
              radius: 20.0,
              child: Container(
                child: Text(
                  item.name[0],
                  style: TextStyle(
                      color: Colors.white, fontWeight: FontWeight.bold),
                ),
              ),
            ),
            title: Container(
              width: 60.0,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  SizedBox(
                    child: Text(
                        item.name,
                        overflow: TextOverflow.ellipsis
                    ),
                    width: 130.0,
                  ),
                  Text("得分： ${item.scores.toString()}"),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
